package pluginMain;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.Socket;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.event.player.AsyncPlayerChatEvent;
@SuppressWarnings("deprecation")
public class RhyChat extends JavaPlugin implements Listener {
	public final String PLUGIN_NAME = "Rhycraft Chat Sync Plugin";
	public final Logger CONSOLE_LOGGER = this.getLogger();
	public Socket socket;
	public send s;
	public Thread pr;
	public recive r;
	public List<String> syncList = new ArrayList<String>();
	public void LOGCONSOLE(String msg) {
		CONSOLE_LOGGER.info(msg);
	}
	public boolean CreateSocketInstance(){
		LOGCONSOLE("Creating socket instance....");
		try {
			socket = new Socket("127.0.0.1", 6666);
			LOGCONSOLE("Success! Now chat serivces was running.");
			return true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			LOGCONSOLE("Connecting failed ! Check your chat sync server!");
			e.printStackTrace();
			return false;
		}
	}
	@Override
	public void onEnable() {
		CreateSocketInstance();
		LOGCONSOLE("Connect to chat sync server....");
		LOGCONSOLE("Create send thread success.");
		s = new send(socket ,this);
		LOGCONSOLE("Create recive thread success.");
		r = new recive(socket, this);
		pr = new Thread(r);
		pr.start();
		this.getServer().getPluginManager().registerEvents(this, this);

		LOGCONSOLE(PLUGIN_NAME + " has been started.");
	}

	@Override
	public void onDisable() {
		try {
			pr.stop();
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			LOGCONSOLE("can't release socket");
		}
		LOGCONSOLE(PLUGIN_NAME + " has been disabled.");
	}

	public String FormatPlayerChat(AsyncPlayerChatEvent e){
		return String.format(e.getFormat(), e.getPlayer().getDisplayName(), e.getMessage());
	}

	@Override
	public boolean onCommand(CommandSender sender, Command command,
			String label, String[] args) {
		if(args.length>0){
			if(args[0].equalsIgnoreCase("reconnect")){
				return CreateSocketInstance();
			}else{
				return false;
			}
		}else{
			LOGCONSOLE("[/rhychat reconnect] to reconnect server.");
			return true;
		}
	}
	@EventHandler(priority=EventPriority.LOWEST)
	public void onPlayerChat(AsyncPlayerChatEvent event) {
		//if (syncList.contains(event.getPlayer().getName())) {
		//	syncList.remove(event.getPlayer().getName());
		//	return;
		//}
		s.setData(event.getPlayer().getName() + "<!!name>" + FormatPlayerChat(event));
		event.setCancelled(true);
	}
	
	public void DisablePlugin(){
		setEnabled(false);
	}

}

class send implements Runnable {
	private Socket connSocket;
	private RhyChat p;
	public send(Socket _s ,RhyChat _p) {
		connSocket = _s;
		p = _p;
	}
	public void setData(String d) {
		try {
			PrintWriter w;
			w = new PrintWriter(new OutputStreamWriter(
					connSocket.getOutputStream()));

			w.write(d);
			w.flush();
		} catch (IOException e) {
			p.LOGCONSOLE("Chat sync server error ! type [/rhychat reconnect] to re-connect to server");
			return;
		}
	}
	@Override
	public void run() {

	}
}

class recive implements Runnable {
	private Socket connSocket;
	private String data;
	private RhyChat p;
	//private FauxChat FauxChater;
	public recive(Socket _s, RhyChat _p) {
		connSocket = _s;
		p = _p;
		//FauxChater = new FauxChat(p.getServer());
	}
	@Override
	public void run() {
		while (!connSocket.isClosed()) {
			try {
				Reader r = new InputStreamReader(connSocket.getInputStream());
				CharBuffer c = CharBuffer.allocate(1024);
				@SuppressWarnings("unused")
				int index = -1;
				while ((index = r.read(c)) != -1) {
					c.flip();
					data = (c.toString());
					String[] chat = data.split("<!!name>", 2);
					//if (!p.syncList.contains(chat[0]))
					//	p.syncList.add(chat[0]);
					//FauxChater.chatWithName(chat[1], chat[0]);
					for(Player h: p.getServer().getOnlinePlayers())
						h.sendMessage(chat[1]);
					p.LOGCONSOLE(chat[0] + " -> " + chat[1]);
					c.clear();
				}
				c.clear();
				r.close();
			} catch (IOException e) {
				p.LOGCONSOLE("Chat sync server error ! type [/rhychat reconnect] to re-connect to server");
				return;
			}
		}

	}
}
